<template>
  <n-modal
    v-model:show="getProps.modalData.show"
    class="custom-card"
    preset="card"
    :style="{ width: '900px' }"
    title="选择员工"
    :bordered="false"
    :segmented="{
      content: true,
      footer: true
    }"
  >
    <x-form ref="formRef" v-model:model="form" inline label-placement="left">
      <n-grid cols="3" x-gap="20">
        <n-form-item-gi label="员工姓名" path="operatorName">
          <n-input v-model:value="form.operatorName" clearable placeholder="请输入" @keyup.enter="handleSubmit" />
        </n-form-item-gi>

        <n-form-item-gi label="手机号" path="operatorMobile">
          <n-input
            v-model:value="form.operatorMobile"
            maxlength="11"
            clearable
            placeholder="请输入"
            @keyup.enter="handleSubmit"
          />
        </n-form-item-gi>

        <n-form-item-gi label="所属部门" path="departmentId">
          <n-select
            v-model:value="form.departmentId"
            :options="department"
            clearable
            filterable
            placeholder="请选择所属部门"
            @update:value="handleSubmit"
          />
        </n-form-item-gi>

        <n-form-item-gi>
          <n-space>
            <n-button type="primary" @click="handleSubmit"> 搜索 </n-button>
            <n-button @click="handleReset"> 重置 </n-button>
          </n-space>
        </n-form-item-gi>
      </n-grid>
    </x-form>

    <x-data-table
      ref="tableRef"
      v-model:immediate="immediate"
      v-model:checked-row-keys="checkedRowKeys"
      :row-props="(rowData) => rowProps(rowData)"
      :max-height="400"
      :toolbar="false"
      :params="paginationParams"
      :columns="columns"
      :row-key="(row) => row.id"
    >
    </x-data-table>

    <template #footer>
      <n-space justify="space-between" align="center">
        <n-text depth="3">
          已选 <n-text type="primary">{{ selectedCount }}</n-text> 个
        </n-text>
        <n-space align="center">
          <n-button @click="handleClose">取消</n-button>
          <n-button type="primary" @click="handleSave">确定</n-button>
        </n-space>
      </n-space>
    </template>
  </n-modal>
</template>

<script setup lang="ts">
  import {
    NModal,
    NGrid,
    NFormItemGi,
    NButton,
    NSpace,
    NInput,
    NText,
    NTag,
    NRadio,
    NSelect,
    useMessage
  } from 'naive-ui'
  import { XForm, XDataTable } from '@/components'
  import { computed, h, onMounted, reactive, ref } from 'vue'
  import { useDictionary } from '@/hooks'
  import { SystemStarrDetail } from '@/api/model/systemModel'
  import { useStore } from '@/store'

  const { get: getDict, find: findDict } = useDictionary()
  const store = useStore()
  const message = useMessage()
  const formRef = ref(null)
  const emits = defineEmits(['success'])
  const props = defineProps({
    modalData: {
      type: Object,
      default: () => ({})
    },

    multiple: {
      type: Boolean,
      default: false
    }
  })
  const getProps = reactive(props)
  const checkedRowKeys = ref([])
  const form = ref({
    keywordType: 1,
    keyword: null,
    productBrand: null,
    categoryId: null,
    productSelect: 0,
    tagsType: 1,
    priceRange: [],
    sortKey: '',
    sortOrder: null,
    displayStatus: null,
    departmentId: null
  })
  const department = computed(() => store.getters.department)
  const tableRef = ref(null)
  const immediate = ref(true)
  const paginationParams = computed(() => {
    return {
      actions: 'system/getSystemStaff',
      data: form.value
    }
  })
  const checkedId = ref(-1)
  const selectedCount = computed(() => {
    if (props.multiple) {
      return checkedRowKeys.value.length
    } else {
      return checkedId.value > 0 ? 1 : 0
    }
  })

  const columns = reactive([
    {
      type: 'selection'
    },
    {
      title: '',
      key: 'radio',
      width: 40,
      render(row: SystemStarrDetail) {
        return h(NRadio, {
          checked: row.id === checkedId.value,
          onChange: () => handleSelectSingleRow(row),
          value: row.id
        })
      }
    },
    {
      title: '员工ID',
      key: 'id'
    },
    {
      title: '员工姓名',
      key: 'operatorName'
    },
    {
      title: '手机号',
      key: 'operatorMobile'
    },
    {
      title: '所属部门',
      key: 'departmentName'
    },
    {
      title: '账号状态',
      key: 'operatorStatus',
      render(row: SystemStarrDetail): any {
        return h(
          NTag,
          {
            round: true,
            size: 'small',
            type: row.operatorStatus ? 'success' : 'error'
          },
          () => findDict(row.operatorStatus, 'OPERATOR_STATUS')
        )
      }
    }
  ])

  onMounted(() => {
    getDict('OPERATOR_STATUS')
    getDepartmentList()

    if (props.multiple) {
      columns.splice(1, 1)
    } else {
      columns.shift()
    }
  })

  async function getDepartmentList() {
    await store.dispatch('system/getSystemDepartment')
  }

  function rowProps(row: SystemStarrDetail) {
    return {
      onClick: () => {
        if (!props.multiple) {
          handleSelectSingleRow(row)
        }
      }
    }
  }

  function handleSubmit() {
    checkedRowKeys.value = []
    immediate.value = true
  }

  function handleReset() {
    formRef.value.resetFields()
    handleSubmit()
  }

  function handleClose() {
    getProps.modalData.show = false
  }

  function handleSave() {
    if (props.multiple) {
      if (checkedRowKeys.value.length === 0) return message.warning('请选择')
      emits('success', checkedRowKeys.value)
    } else {
      if (checkedId.value < 0) return message.warning('请选择')
      emits('success', checkedId.value)
    }
  }

  function handleSelectSingleRow(row: SystemStarrDetail) {
    checkedId.value = row.id
  }
</script>

<style scoped lang="scss"></style>
